Factory and Observer
import javax.swing.*; import java.awt.*; import java.awt.event.*; class form extends JFrame{ JTextField tname; JTextField taddress; public form(){ tname = new JTextField(20);tname.setBounds(20,20,100,25); taddress = new JTextField(20);taddress.setBounds(20,50,100,25); setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); add(tname); add(taddress); setSize(400,400); } } class bac_form extends form{ JTextField jschool; public bac_form(){ jschool = new JTextField("Enter School");jschool.setBounds(20,80,100,25); add(jschool); } } class mas_form extends form{ JTextField jcollege; public mas_form(){ jcollege = new JTextField("Enter College");jcollege.setBounds(20,80,100,25); add(jcollege); } } class form_factory{ form f; public form_factory(){ //f = new form(); } public form getForm(String type){ switch(type){ case "bachelor": f = new bac_form(); break; case "master": f = new mas_form(); break; } return f; } } class gui extends JFrame{ JButton jbbac,jbmas; public gui(){ setLayout(null); setSize(300,300); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jbbac = new JButton("Bachelor");jbbac.setBounds(20,20,100,25); jbmas = new JButton("Master");jbmas.setBounds(130,20,100,25); add(jbbac); add(jbmas); jbbac.addActionListener(new formFactory_demo("bachelor")); jbmas.addActionListener(new formFactory_demo("master")); } } class formFactory_demo implements ActionListener{ String level; form_factory ff; static form f; public formFactory_demo(String level){ ff = new form_factory(); this.level = level; } public void actionPerformed(ActionEvent ae){ f = ff.getForm(level); } public static void main(String[] aa){ gui g = new gui(); } }
Observer
import java.util.*; interface students{ public void setName(String n); public String getName(); public void getNotification(); } class student implements students { String name; String message; teacher t; public student(){} public student(teacher t){ this.t = t; this.t.register(this); } public void setName(String name){ this.name = name; } public String getName(){return name;} public void getNotification(){ this.message = t.getMessage(); System.out.println(name+" Message: "+this.message); } } class teacher{ String message; ArrayListlist; public teacher(){list = new ArrayList ();} public void updateMessage(String message){ this.message = message; notifyall(); } public String getMessage(){return message;} public void register(students s){list.add(s);} public void notifyall(){ for (students s : list) { s.getNotification(); } } } class observer{ public static void main(String[] para){ teacher t = new teacher(); student s = new student(t);s.setName("Anil"); student s1 = new student();s1.setName("Laxmi"); student s2 = new student(t);s2.setName("Prabin"); student s3 = new student(t);s3.setName("Soheel"); t.updateMessage("Today is holiday!!!"); } }